﻿using System;
using Fluffy.Library.DocumentContainer;
using Fluffy.Library.Mvvm;
using Fluffy.Text;

namespace Fluffy.FileMenuCommands
{
	public class NewCommandViewModel : ViewModelBase
	{
		private readonly NewCommandModel _model;
		private readonly DocumentContainerViewModel[] _documents =
		{
			new DocumentContainerViewModel(new TextDocument()),
		};

		internal NewCommandViewModel(NewCommandModel model)
		{
			_model = model;

			for (int index = 0; index < _documents.Length; index++)
			{
				DocumentContainerViewModel document = _documents[index];
				document.Selected += OnDocumentSelected;
			}
		}

		private void OnDocumentSelected(IDocumentContainer target)
		{
			for (int index = 0; index < _documents.Length; index++)
			{
				DocumentContainerViewModel document = _documents[index];
				document.IsSelected = false;
			}

			_model.CreateNew(target);
		}

		public DocumentContainerViewModel[] Documents
		{
			get { return _documents; }
		}
	}

	public class DocumentContainerViewModel : ViewModelBase
	{
		private readonly IDocumentContainer _document;
		private bool _isSelected;

		public event Action<IDocumentContainer> Selected;

		public DocumentContainerViewModel(IDocumentContainer document)
		{
			_document = document;
		}

		public string Title
		{
			get { return _document.Title; }
		}

		public bool IsSelected
		{
			get { return _isSelected; }
			set
			{
				if (_isSelected == value)
					return;

				_isSelected = value;
				OnPropertyChanged("IsSelected");

				if (_isSelected && Selected != null)
				{
					Selected(_document);
				}
			}
		}
	}
}
